package com.bbzn.device.client.utils;

import com.alibaba.fastjson.JSONObject;
import com.bbzn.device.client.config.Oauth2Constant;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author wulongbo
 * @Date 2021/12/10 11:33
 * @Version 1.0
 */
public class HttpUtils {

    /**
     * @param url
     * @param headerMap  header 参数
     * @param contentMap body 参数
     * @return
     */
    public static String postMap(String url, Map<String, String> headerMap, Map<String, String> contentMap) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
//        List<NameValuePair> content = new ArrayList<NameValuePair>();
//        Iterator iterator = contentMap.entrySet().iterator();           //将content生成entity
//        while (iterator.hasNext()) {
//            Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
//            content.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
//        }
        CloseableHttpResponse response = null;
        try {
            Iterator headerIterator = headerMap.entrySet().iterator();          //循环增加header
            while (headerIterator.hasNext()) {
                Map.Entry<String, String> elem = (Map.Entry<String, String>) headerIterator.next();
                post.addHeader(elem.getKey(), elem.getValue());
            }
            // 配置请求参数实例
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
                    .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
                    .setSocketTimeout(60000)// 设置读取数据连接超时时间
                    .build();
            // 为httpPost实例设置配置
            post.setConfig(requestConfig);
            // 设置请求头
            post.addHeader("Content-Type", "application/json");
            post.setEntity(new StringEntity(JSONObject.toJSONString(contentMap), ContentType.create("application/json", "utf-8")));
            post.setHeader("Content-Type", "application/json");
//            if (content.size() > 0) {
//                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(content, "UTF-8");
//                StringEntity stringEntity= new StringEntity(contentMap.toString(), "UTF-8");
//                post.setEntity(stringEntity);
//            }
            response = httpClient.execute(post);            //发送请求并接收返回数据
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();       //获取response的body部分
                result = EntityUtils.toString(entity);          //读取reponse的body部分并转化成字符串
            }
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }



    /**
     * @param url
     * @param headerMap  header 参数
     * @param jsonString body 参数
     * @return
     */
    public static String postMap(String url, Map<String, String> headerMap, String jsonString) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            Iterator headerIterator = headerMap.entrySet().iterator();          //循环增加header
            while (headerIterator.hasNext()) {
                Map.Entry<String, String> elem = (Map.Entry<String, String>) headerIterator.next();
                post.addHeader(elem.getKey(), elem.getValue());
            }
            // 配置请求参数实例
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
                    .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
                    .setSocketTimeout(60000)// 设置读取数据连接超时时间
                    .build();
            // 为httpPost实例设置配置
            post.setConfig(requestConfig);
            // 设置请求头
            post.addHeader("Content-Type", "application/json");
            post.setEntity(new StringEntity(jsonString, ContentType.create("application/json", "utf-8")));
            post.setHeader("Content-Type", "application/json");
            response = httpClient.execute(post);            //发送请求并接收返回数据
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();       //获取response的body部分
                result = EntityUtils.toString(entity);          //读取reponse的body部分并转化成字符串
            }
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }




    // url格式转map
    public static Map<String, String> paramToMap(String paramStr) {
        String[] params = paramStr.split("&");
        Map<String, String> resMap = new HashMap<String, String>();
        for (int i = 0; i < params.length; i++) {
            String[] param = params[i].split("=");
            if (param.length >= 2) {
                String key = param[0];
                String value = param[1];
                for (int j = 2; j < param.length; j++) {
                    value += "=" + param[j];
                }
                resMap.put(key, value);
            }
        }
        return resMap;
    }

    //Header字符串转map
    public static Map<String, String> splid(String zz) {
        String[] stepOne = zz.split("\n");
        Map<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < stepOne.length; i++) {
            String[] stepTwo = stepOne[i].split(": ");
            if (map.get(stepTwo[0]) == null) {
                map.put(stepTwo[0], stepTwo[1]);
            } else {
                map.put(stepTwo[0], stepTwo[1] + "," + map.get(stepTwo[0]));
            }
        }
        return map;
    }

//    public static void main(String[] args) {
//        String topic = Oauth2Constant.GROUP_PRE + 9 + "/" + System.currentTimeMillis();
//        String authorization = GetSecret.getHeader();
//        String url = "tcp://47.106.90.231:1883";
//        String postUri = Oauth2Constant.EMQ_API_HTTP
//                + url.substring(0, url.lastIndexOf(":")).substring(url.indexOf(":")) + Oauth2Constant.EMQ_API_SUBSCRIBE_ADR;
//        Map<String, String> headerMap = new HashMap<>();
//        headerMap.put("Authorization", authorization);
//        Map<String, String> contentMap = new HashMap<>();
//        contentMap.put("topics", topic);
//        contentMap.put("qos", "2");
//        contentMap.put("clientid", "android_362523432447145");
//        String s =postMap(postUri, headerMap, contentMap);
//        System.out.println(s);
//
//    }

}
